<template>
  <div class="container">
    <div class="header">设备实时工速</div>
    <div class="echart-container">
      <div ref="echartsBox" class="echarts-box"></div>
    </div>
  </div>
</template>

<script setup>
  import { ref, getCurrentInstance } from 'vue';
  import commomOption from './commomOption.ts';
  import * as echarts from 'echarts';
  var xData = ['数据1', '12:06', '12:07', '12:08', '12:09', '12:10'];
  const dataList = [
    [1000, 1300, 1200, 700, 600, 700],
    [700, 800, 900, 800, 700, 400],
    [400, 300, 500, 200, 200, 300],
    [300, 200, 400, 100, 400, 200],
  ];
  const series = [];
  let totalNum = 0;
  dataList.forEach((data, idx) => {
    const serie = {
      name: `data${idx}`,
      type: 'bar',
      barWidth: '50%',
      stack: 'asset',
      barWidth: 15,
      barGap: 0.4, //柱间距离
      data: data,
    };
    if (dataList.length === idx + 1) {
      totalNum = 0;
      serie.label = {
        normal: {
          // 重写未完成label，通过计算属性重新给formatter赋值，返回
          show: true, // 计算的总数
          position: 'right',
          formatter: function (params) {
            return dataList.reduce((cur, data) => {
              return data[params.dataIndex] + cur;
            }, 0);
          },
          textStyle: { color: '#3EFFE8' },
        },
      };
    }
    series.push(serie);
  });
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow',
      },
      textStyle: {
        fontWeight: 'normal',
        fontSize: '100%',
      },
    },
    grid: commomOption.grid,
    legend: commomOption.legend,
    color: [
      'rgba(21, 93, 92, 1)',
      'rgba(33, 139, 132, 1)',
      'rgba(44, 186, 172, 1)',
      'rgba(62, 255, 232, 1)',
      '#0efde1',
      '#0efd6e',
    ],
    xAxis: Object.assign({}, commomOption.yAxis, {
      type: 'value',
    }),
    yAxis: Object.assign({}, commomOption.yAxis, {
      type: 'category',
      data: xData,
    }),
    series: series,
  };

  // 在Vue3中，getCurrentInstance()可以用来获取当前组件实例
  const { proxy } = getCurrentInstance();
  // 获取echart挂载的DOM节点
  const echartsBox = ref();
  // echartsf弹窗出现
  function echartInit() {
    //nextTick后再调用，不然会报错
    nextTick(() => {
      // echarts初始化
      let myChart = proxy.$echarts.init(echartsBox.value);

      option && myChart.setOption(option);

      // 根据页面大小自动响应图表大小
      window.addEventListener('resize', function () {
        myChart.resize();
      });
    });
  }

  echartInit();
</script>
<style lang="less" scoped>
  @import url(./container.less);
</style>
